package cn.shop.transcation.promotionsModule;

import cn.hutool.core.util.RandomUtil;
import cn.shop.base.BaseEntity;
import com.baomidou.mybatisplus.annotation.TableField;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;

import java.math.BigDecimal;
import java.util.*;

@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
public class PrizeRule extends BaseEntity {

    /**
     * 活动编号
     */
    private Long pid;
    /**
     * 规则key
     */
    @TableField("`key`")
    private String key;
    /**
     * 中奖几率
     */
    private double ratio;
    /**
     * 奖品
     */
    private String prize;

    @TableField(exist = false)
    private static final int mulriple = 1000000;
    public static PrizeRule pay(List<PrizeRule> aWards) {
        if (aWards == null) {
            aWards = new ArrayList<>();
        }
        if (aWards.size() == 1) {
            return aWards.get(0);
        }
        int lastScope = 0;
        // 洗牌，打乱奖品次序
        Collections.shuffle(aWards);
        Map<Long, int[]> prizeScopes = new HashMap<>();
        Map<Long, PrizeRule> prizeQuantity = new HashMap<>();
        for (PrizeRule award : aWards) {
            Long prizeId = award.getId();
            BigDecimal ratio = BigDecimal.valueOf(award.getRatio());
            if ((ratio.compareTo(new BigDecimal(0))) > 0) {
                // 划分区间
                int currentScope = lastScope + ratio.multiply(new BigDecimal(mulriple)).intValue();
                prizeScopes.put(prizeId, new int[]{lastScope + 1, currentScope});
                prizeQuantity.put(prizeId, award);
                lastScope = currentScope;
            }
        }
        // 获取1-1000000之间的一个随机数
        int luckyNumber = RandomUtil.randomInt(mulriple) + 1;
        PrizeRule luckyResult = null;
        // 查找随机数所在的区间
        if (!prizeScopes.isEmpty()) {
            Set<Map.Entry<Long, int[]>> set = prizeScopes.entrySet();
            for (Map.Entry<Long, int[]> m : set) {
                Long key = m.getKey();
                int[] val = m.getValue();
                if (luckyNumber >= val[0] && luckyNumber <= val[1]) {
                    luckyResult = prizeQuantity.get(key);
                    break;
                }
            }
        }
        if (luckyResult == null) {
            // 奖品库存减一
            System.out.println("--------------   " + luckyNumber);
        }
        return luckyResult;
    }
}
